$(function () {
    // 重置窗口大小
    function resizeWindow() {
        var DEBUG;
        //DEBUG = true;
        if (DEBUG) {
            [].forEach.call($($('*')), function (a) {
                a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
            });
        }
        //console.log('resize...');
        $('#mainright').outerWidth($('#main').width() - $('#mainleft').width() - 10 - 20);
        //$('#main').outerHeight($('body').outerHeight() - $('.RightMainTitle').outerHeight() - parseInt($('#main').css('margin-top')) - parseInt($('#main').css('margin-bottom')));
        //$('#mytable').outerWidth($('#mainright').width() - $('#mytable2').outerWidth() - 15);
        //$('#zhezhao').height(window.innerHeight)
        $('#zhezhao').css({
            height: window.innerHeight,
            width: $('body').width()
        });
    }
    resizeWindow();
    // resize窗口
    window.onresize = function () {
        resizeWindow();
    };

    var id = 1;
    // 获取资源目录数据
    window.getData = function (data, callback) {
        $.ajax({
            type: "post",
            async: true,
            url: "/BaseAshx/Resource/ResourceAshx.ashx",
            data: data,
            datatype: "json",
            success: function (result) {
                //  console.log(result);
                result = result.split('||');
                if (result[0] == 200) {
                    result = JSON.parse(result[2]);
                    callback(result);
                } else {
                    console.log(result[1]);
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    };

    var zTreeObj;
    // ztree 配置参数
    var setting = {
        view: {
            showIcon: false,
            showLine: false,
            expandSpeed: 10,
        },
        callback: {
            onClick: function (event, treeId, treeNode, cliclFlag) {
                $('#mytbody').html('');
                nowNodeId = treeNode.id;
                // console.log(event, treeId, treeNode, cliclFlag);
                if (treeNode.isParent) {
                    // 当前全部节点数据
                    var treeObj = $.fn.zTree.getZTreeObj('ztree');
                    // 当前点击节点
                    var parentZNode = treeObj.getNodeByParam('id', treeNode.id, null);
                    // 当前节点没有加载过
                    if (!parentZNode.wasOpened) {
                        // 请求数据
                        getData({
                            stype: '查找下级目录',
                            id: treeNode.id,
                        }, function (result) {
                            result.map(function (ite, index) {
                                ite.id = ite.ID;
                                ite.name = ite.NAME;
                                ite.isParent = ite.ISPARENT;
                                delete ite.ID;
                                delete ite.NAME;
                                delete ite.ISPARENT;
                            });
                            treeObj.removeChildNodes(parentZNode);
                            newNode = treeObj.addNodes(parentZNode, result, true);
                            //newNode = treeObj.updateNode(result);
                            parentZNode.wasOpened = true;
                            updateRignt(treeNode.children);
                        });
                    } else {
                        updateRignt(treeNode.children);
                    }
                    nowNodeId = parentZNode.id;
                }
            },
            onExpand: function (event, treeId, treeNode, cliclFlag) {
                // console.log(event, treeId, treeNode, cliclFlag);
                // 当前全部节点数据
                var treeObj = $.fn.zTree.getZTreeObj('ztree');
                // 当前点击节点
                var parentZNode = treeObj.getNodeByParam('id', treeNode.id, null);
                // 当前节点没有加载过
                if (!parentZNode.wasOpened) {
                    // 请求数据
                    getData({
                        stype: '查找下级目录',
                        id: treeNode.id,
                    }, function (result) {
                        result.map(function (ite, index) {
                            ite.id = ite.ID;
                            ite.name = ite.NAME;
                            ite.isParent = ite.ISPARENT;
                            delete ite.ID;
                            delete ite.NAME;
                            delete ite.ISPARENT;
                        });
                        treeObj.removeChildNodes(parentZNode);
                        newNode = treeObj.addNodes(parentZNode, result, false);
                        // newNode = treeObj.updateNode(result);
                        parentZNode.wasOpened = true;
                    });
                }
            },
        }
    };

    // 首次请求数据(初始化)
    getData({
        stype: '初始化资源目录管理'
    }, function (result) {
        // ztree 属性参数
        var zNodes = result.map(function (ite, index) {
            ite.id = ite.ID;
            ite.name = ite.NAME;
            ite.isParent = ite.ISPARENT;
            delete ite.ID;
            delete ite.NAME;
            delete ite.ISPARENT;
            if (ite.isParent) {
                ite.iconClose = '/img/BasePlatform/expand.png';
                ite.iconOpen = '/img/BasePlatform/collapse.png';
                ite.icon = '/img/BasePlatform/collapse.png';
            }
            return ite;
        });
        zTreeObj = $.fn.zTree.init($('#ztree'), setting, zNodes);
    });

    // 点击资源目录按钮
    $('.opraButton').on('click', function () {
        var treeObj = $.fn.zTree.getZTreeObj('ztree');
        var nodes = treeObj.getNodesByFilter(function (node) {
            return node.level == 0;
        });
        updateRignt(nodes);
        nowNodeId = 'ztree';
    });

    // 更新右侧子目录管理
    var checkSameNodes = [];

    function updateRignt(nodes) {
        checkSameNodes = nodes;
        // console.log(nodes);
        nowNode = nodes;
        var html = '';
        if (nodes) {
            nodes.forEach(function (ite, index) {
                html += '<tr style="height:30px;"><td style="border:1px solid black;">' + (index + 1) + '</td><td style="border:1px solid black;">' + ite.name + '</td><td style="border:1px solid black;"><a myId="' + ite.id + '" class="changeCatalog">修改目录</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a myId="' + ite.id + '" class="deleteCatalog">删除目录</a></td></tr>';
            });
        }
        $('#mytbody').html(html);
    }

    // 取消遮罩
    $('#zhezhao').on('click', function (e) {
        if (e.target.id == 'zhezhao') {
            hideZhezhao();
        }
    });

    function hideZhezhao() {
        $('#zhezhao').hide();
        $('#inputDiv input').val('');
        $('#myh1').html('');
    }

    // 当前选中node的id
    var nowNodeId;
    var submitType;
    // 点击添加子目录
    $('#addCatalog').on('click', function () {
        if (nowNodeId) {
            submitType = 'add';
            $('#zhezhao').show();
        } else {
            alert('请先选中目录');
        }
    });

    // 点击提交按钮
    $('#submitName').on('click', function () {
        var value = $('#inputDiv input').val();
        if (value) {
            // 添加
            if (submitType == 'add') {
                addCatalog(value);
            } else if (submitType == 'change') {
                // 修改
                var $this = $(this);
                var myid = $this.attr('myid');
                var name = $this.attr('name');
                confirm('确认要将“' + name + '”改为“' + value + '”吗？');
                changeCatalog(value, myid, name);
            }
        } else {
            alert('请输入目录名');
        }
    });

    // 点击删除目录
    $('#mytbody').on('click', '.deleteCatalog', function (e) {
        var $target = $(e.target);
        var name = $target.parent().prev().html();
        confirm('确认要删除“' + name + '”吗？');
        deleteCatalog($target.attr('myid'));
    });

    // 点击修改目录、
    $('#mytbody').on('click', '.changeCatalog', function (e) {
        var $target = $(e.target);
        var myid = $target.attr('myid');
        var name = $target.parent().prev().html();
        submitType = 'change';
        $('#zhezhao').show();
        $('#submitName').attr({
            'myid': myid,
            'name': name,
        });
    });

    // 添加子目录
    function addCatalog(value) {
        var name = $('#nameInput').val();
        var hasSameName = false;
        checkSameNodes.map(function (ite, index) {
            if (name == ite.name) {
                hasSameName = true;
            }
        });
        if (hasSameName) {
            alert(name + '已存在,请修改后再提交');
        } else {
            var id = nowNodeId;
            if (nowNodeId == 'ztree') {
                id = '';
            }
            // 当前全部节点数据
            var treeObj = $.fn.zTree.getZTreeObj('ztree');
            // 当前点击节点
            var parentZNode = treeObj.getNodeByParam('id', nowNodeId, null);
            var hadChilds = '';
            if (nowNodeId != 'ztree') {
                hadChilds = parentZNode.isParent;
            }
            // 添加接口
            $.ajax({
                type: "post",
                async: true,
                url: "/BaseAshx/Resource/ResourceAshx.ashx",
                data: {
                    stype: '添加目录',
                    id: id,
                    name: name,
                    hadChilds: hadChilds
                },
                datatype: "json",
                success: function (result) {
                    // console.log(result);
                    result = result.split('||');
                    if (result[0] == 200) {
                        var id = result[2];
                        // 成功
                        result = [{
                            id: id,
                            name: name,
                            isParent: false
                        }];


                        //var parentZNode = treeObj.getNodeByParam('id', nowNodeId, null);
                        newNode = treeObj.addNodes(parentZNode, result, true);
                        var nodes = treeObj.getNodesByFilter(function (node) {
                            return node.level == 0;
                        });
                        if (nowNodeId == 'ztree') {
                            updateRignt(nodes);
                        } else {
                            updateRignt(parentZNode.children);
                        }
                        hideZhezhao();
                    } else {
                        console.log(result[1]);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }
    }

    // 删除目录
    function deleteCatalog(myid) {
        // 当前全部节点数据
        var treeObj = $.fn.zTree.getZTreeObj('ztree');
        // 当前点击节点
        var myNode = treeObj.getNodeByParam('id', myid, null);
        var childCount = '';
        if (myNode.getParentNode()) {
            childCount = myNode.getParentNode().children.length;
        }
        // 删除接口
        $.ajax({
            type: "post",
            async: true,
            url: "/BaseAshx/Resource/ResourceAshx.ashx",
            data: {
                stype: '删除目录',
                id: myid,
                childCount: childCount
            },
            datatype: "json",
            success: function (result) {
                // console.log(result);
                result = result.split('||');
                if (result[0] == 200) {
                    // 成功后
                    newNode = treeObj.removeNode(myNode);

                    var parentZNode = treeObj.getNodeByParam('id', nowNodeId, null);

                    var nodes = treeObj.getNodesByFilter(function (node) {
                        return node.level == 0;
                    });
                    if (nowNodeId == 'ztree') {
                        updateRignt(nodes);
                    } else {
                        updateRignt(parentZNode.children);
                    }
                } else {
                    console.log(result[1]);
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    }

    // 修改目录
    function changeCatalog(value, myid, name) {
        // name是旧的,value是新的,myid是当前节点
        var hasSameName = false;
        checkSameNodes.map(function (ite, index) {
            if (value == ite.name) {
                hasSameName = true;
            }
        });
        if (hasSameName) {
            alert(value + '已存在,请修改后再提交');
        } else {
            var id = myid;
            if (myid == 'ztree') {
                id = '';
            }
            // 修改接口
            $.ajax({
                type: "post",
                async: true,
                url: "/BaseAshx/Resource/ResourceAshx.ashx",
                data: {
                    stype: '修改目录',
                    id: id,
                    name: value
                },
                datatype: "json",
                success: function (result) {
                    // console.log(result);
                    result = result.split('||');
                    if (result[0] == 200) {
                        var id = result[2];
                        // 当前全部节点数据
                        var treeObj = $.fn.zTree.getZTreeObj('ztree');
                        // 当前点击节点
                        var myNode = treeObj.getNodeByParam('id', myid, null);
                        myNode.name = value;
                        myNode.id = id;
                        newNode = treeObj.updateNode(myNode);
                        var parentZNode = treeObj.getNodeByParam('id', nowNodeId, null);
                        var nodes = treeObj.getNodesByFilter(function (node) {
                            return node.level == 0;
                        });
                        if (nowNodeId == 'ztree') {
                            updateRignt(nodes);
                        } else {
                            updateRignt(parentZNode.children);
                        }
                        hideZhezhao();
                    } else {
                        console.log(result[1]);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }
    }
});